package de.sendorian.app.forumArchive;

import java.io.IOException;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import de.sendorian.app.forumArchive.domain.Forum;
import de.sendorian.app.forumArchive.download.Downloader;
import de.sendorian.app.forumArchive.repository.ForumRepository;


/**
 * Central class that manages the indexing and downloading.
 * 
 * @author sendorian
 * 
 */
@Component
public class ArchiveBuilder implements Runnable {

    private static Logger LOG = Logger.getLogger(ArchiveBuilder.class);

    private ForumRepository forumRepository;
    private ForumUpdater forumUpdater;
    private Downloader downloader;
    private Compressor compressor;
    private Cleaner cleaner;


    public static void main(String[] args) throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
        String runBean;
        if (args != null && args.length > 0) {
            runBean = args[0];
        } else {
            runBean = "archiveBuilder";
        }
        Runnable mainClass = (Runnable) context.getBean(runBean);
        mainClass.run();
    }


    public void run() {
        forumUpdater.updateAllForums();
        
        List<Forum> forums = forumRepository.findAll();
        downloader.downloadForums(forums);
        compressor.compressImages(forums);
        cleaner.run();

        forumRepository.shutdownDatabase();
        LOG.info("Finished!");
    }


    @Autowired
    public void setForumRepository(ForumRepository forumRepository) {
        this.forumRepository = forumRepository;
    }
    
    
    @Autowired
    public void setForumUpdater(ForumUpdater forumUpdater) {
        this.forumUpdater = forumUpdater;
    }


    @Autowired
    public void setDownloader(Downloader downloader) {
        this.downloader = downloader;
    }


    @Autowired
    public void setCompressor(Compressor compressor) {
        this.compressor = compressor;
    }


    @Autowired
    public void setCleaner(Cleaner cleaner) {
        this.cleaner = cleaner;
    }
}
